package client;

import game.BigClick;
import game.MagicObject;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

import javax.swing.JPanel;
import javax.swing.JToggleButton;

/**
 * Affiche les objets magiques
 * @author Julien Roch
 * @version 1.0
 */
public class JPanelMagicObjects extends JPanel{
	
	private ClientInternals internals;
	/**
	 * Constructeur
	 * @param objects La liste d'objets magiques
	 * @param internals Le mod�le cote client
	 */
	public JPanelMagicObjects(Map<Class, Integer> objects, ClientInternals internals){
		this.internals = internals;
	}
	/**
	 * Bouton d'un objet magique
	 *
	 */
	class ObjectButton extends JToggleButton{
		// La classe de l'objet
		private Class c;
		/**
		 * 
		 * @param c Classe de l'objet
		 */
		public ObjectButton(Class c){
			this.c = c;
			// todo add objects drawings
			this.setPreferredSize(new Dimension(32, 32));
			if(JPanelMagicObjects.this.internals.getMagicObjects().get(c)>0){
				this.setEnabled(true);
			}else{
				this.setEnabled(false);
			}
			if(c.isInstance(JPanelMagicObjects.this.internals.getObjectToPlay())){
				this.setSelected(true);
			}else{
				this.setSelected(false);
			}
			
			// action listener
			this.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
										
					if(ObjectButton.this.isSelected()){
						if(BigClick.class.equals(ObjectButton.this.c)){
							MagicObject o = JPanelMagicObjects.this.internals.getObject(new BigClick(null,0));
							JPanelMagicObjects.this.internals.setObjectToPlay(o);
						}
					}else{
						if(BigClick.class.equals(ObjectButton.this.c) &&
								BigClick.class.isInstance(JPanelMagicObjects.this.internals.getObjectToPlay())){
							JPanelMagicObjects.this.internals.putObject(new BigClick(null,0));
						}
					}
				}
			});
			
			this.revalidate();
			this.repaint();
			this.setBackground(Color.BLACK);
		}
		
		protected void paintComponent(Graphics g) {
			super.paintComponents(g);
			if(c.equals(BigClick.class)){
				BigClick bc = new BigClick(null,0);
				bc.drawButton(g, this.getSize(), this);
			}
		}
	}
	/**
	 * Rafraichit la liste des boutons
	 */
	public void refresh() {
		this.removeAll();
		if(this.internals.getMagicObjects()==null || this.internals.getMagicObjects().size()==0)
			return;
		
		// calcul de la taille de la grille
		int w = this.internals.getMagicObjects().keySet().size();
		int h = (w+3)/4;
		w = Math.min(w, 4);
		
		this.setLayout(new GridLayout(w,h));
		for(Class c : this.internals.getMagicObjects().keySet()){
			this.add(new ObjectButton(c));
		}
		this.setVisible(true);
		this.revalidate();
		this.repaint();
	}
	
}
